package com.huawei.cloudapp.ui.fragment.mine;

import static android.content.Context.MODE_PRIVATE;
import static com.huawei.cloudapp.utils.CasConstantsUtil.COMMON;
import static com.huawei.cloudapp.utils.CasConstantsUtil.IAM_USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PROJECT_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN_EXPIRE_TIME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USER_INFO;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;
import com.huawei.cloudapp.R;
import com.huawei.cloudapp.common.CasCommonDialog;
import com.huawei.cloudapp.common.CasRecord;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.ui.activity.CasCloudLoginActivity;
import com.huawei.cloudapp.ui.activity.mine.MineAboutActivity;
import com.huawei.cloudapp.ui.activity.mine.MineGuideActivity;
import com.huawei.cloudapp.ui.activity.mine.MineQuestionActivity;
import com.huawei.cloudapp.ui.common.ButtonTouchStyleListener;
import com.huawei.cloudapp.ui.fragment.CloudPhoneFragment;
import com.huawei.cloudapp.utils.CasCommonUtils;

public class MineFragment extends CloudPhoneFragment {

    private static final String TAG = "MineFragment";
    private CasRecord mUserCasRecord;
    private User mUser;
    private boolean isLogin;
    private CasCommonDialog mDialog;
    private LinearLayout mLayout;
    private CasRecord mCommonCasRecord;
    private Button logoutButton;
    private boolean isReadyToExit = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.e(TAG, "onCreate: ");
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView: ");
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        mUserCasRecord = new CasRecord(getActivity().getSharedPreferences(USER_INFO, MODE_PRIVATE));
        String username = mUserCasRecord.getRecord(USERNAME);
        if (username == null || username.isEmpty()) {
            finishAndReLogin(true);
        } else {
            mUser = new User(username,
                    mUserCasRecord.getRecord(IAM_USERNAME),
                    mUserCasRecord.getHashMapRecord(TOKEN),
                    mUserCasRecord.getHashMapRecord(TOKEN_EXPIRE_TIME),
                    mUserCasRecord.getHashMapRecord(PROJECT_ID),
                    "");
            isLogin = true;
        }
        return view;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.e(TAG, "onViewCreated: ");
        super.onViewCreated(view, savedInstanceState);
        mLayout = view.findViewById(R.id.fragment_mine);
        mCommonCasRecord = new CasRecord(view.getContext().getSharedPreferences(COMMON, MODE_PRIVATE));

        // 圆形头像
        ImageView headImage = view.findViewById(R.id.head);
        Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.head);
        Bitmap bitmap2 = CasCommonUtils.makeBitmapSquare(bitmap1, 120);
        RoundedBitmapDrawable roundImg = RoundedBitmapDrawableFactory.create(getResources(), bitmap2);
        roundImg.setAntiAlias(true);
        roundImg.setCornerRadius(bitmap2.getWidth() / 2);
        headImage.setImageDrawable(roundImg);

        RelativeLayout aboutLinear = view.findViewById(R.id.mine_about_linear);
        aboutLinear.setOnTouchListener(new ButtonTouchStyleListener());
        aboutLinear.setOnClickListener(new SwitchFragmentClickListener());

        RelativeLayout guideLinear = view.findViewById(R.id.mine_guide_linear);
        guideLinear.setOnTouchListener(new ButtonTouchStyleListener());
        guideLinear.setOnClickListener(new SwitchFragmentClickListener());

        RelativeLayout questionLinear = view.findViewById(R.id.mine_question_linear);
        questionLinear.setOnTouchListener(new ButtonTouchStyleListener());
        questionLinear.setOnClickListener(new SwitchFragmentClickListener());

        logoutButton = view.findViewById(R.id.logout);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onLogOut();
            }
        });

        fillUserInfo(view);

        fillSdkVersion(view, getContext());

    }

    private void fillUserInfo(@NonNull View view) {
        if (mUser != null) {
            TextView iamUserNameTextView = view.findViewById(R.id.iam_user_name);
            iamUserNameTextView.setText(mUser.getIamUsername());

            TextView userNameTextView = view.findViewById(R.id.user_name);
            userNameTextView.setText(mUser.getUsername());
        }
    }

    private void fillSdkVersion(View view, Context context) {
        TextView sdkTextView = view.findViewById(R.id.sdk_version);
        sdkTextView.setText(CasCommonUtils.getApkVersion(context));
    }

    private void finishAndReLogin(boolean isPrompt) {
        if (isPrompt) {
            //提示客户需要重新登陆
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastParams params = new ToastParams();
                    params.text = getResources().getString(R.string.user_info_invalid_need_login);
                    params.style = new CustomToastStyle(R.layout.toast_error);
                    Toaster.show(params);
                }
            });
        }
        getActivity().getSharedPreferences(USER_INFO, MODE_PRIVATE).edit().clear().apply();
        Intent intent = new Intent(getActivity(), CasCloudLoginActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void onResume() {
        Log.e(TAG, "onResume: ");
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        Log.e(TAG, "onDestroyView: ");
        super.onDestroyView();
    }

    private void onLogOut() {
        if (!isLogin) {
            finishAndReLogin(false);
        } else {
            String name = mUser.getUsername();
            if (!mUser.getIamUsername().isEmpty()) {
                name = mUser.getIamUsername();
            }
            showLogoutUserDialog(name);
        }
    }

    public void showLogoutUserDialog(String username) {
        if (mDialog == null || !mDialog.isShowing()) {
            final View contentView = View.inflate(getContext(), R.layout.cas_set_ui_level, null);
            final CasCommonDialog.Builder builder = new CasCommonDialog.Builder(getContext());
            CasCommonDialog.DialogClickListener dialogListener = new CasCommonDialog.DialogClickListener();

            builder.setTitle(username);
            builder.setMessage(getResources().getString(R.string.is_exit_account));
            builder.setContentView(contentView);
            builder.setPositiveButton(getResources().getString(R.string.cas_phone_cancel_tip_message), dialogListener);
            builder.setNegativeButton(getResources().getString(R.string.cas_phone_quit_app_tip_message), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finishAndReLogin(false);
                }
            });

            mDialog = builder.create();
            mDialog.setCancelable(true);
            if (!getActivity().isFinishing()) {
                mDialog.show();
            }
        }
    }

    @Override
    public boolean onBackPressed() {
        if (mDialog != null &&  mDialog.isShowing()) {
            mDialog.dismiss();
            return true;
        }
        if (!isReadyToExit) {
            Toaster.show(R.string.cas_exit_app_confirmation);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isReadyToExit = false;
                }
            }, 2000);
            isReadyToExit = true;
            return true;
        } else {
            return false;
        }
    }

    class SwitchFragmentClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.mine_about_linear:
                    startActivity(new Intent(getActivity(), MineAboutActivity.class));
                    break;
                case R.id.mine_guide_linear:
                    startActivity(new Intent(getActivity(), MineGuideActivity.class));
                    break;
                case R.id.mine_question_linear:
                    startActivity(new Intent(getActivity(), MineQuestionActivity.class));
                    break;
            }
        }
    }
}
